<template>
  <div class="user-main">
    <div class="user-header">
      <el-form :inline="true">
        <el-form-item v-if="hasAuth('user:list')">按信息搜索</el-form-item>
        <el-form-item v-if="hasAuth('user:list')">
          <el-input :placeholder="searchType"
                    v-model="search"
                    class="input-with-select"
                    @change="changeSearchInput"
                    :clearable=true>
            <el-select v-model="searchType" slot="prepend">
              <el-option label="姓名" value="name"></el-option>
              <el-option label="电话号码" value="phone"></el-option>
              <el-option label="邮箱" value="email"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
          </el-input>
        </el-form-item>

        <el-form-item v-if="hasAuth('user:add')">
          <el-button type="primary" @click="editUser(null,null)">新增用户</el-button>
        </el-form-item>

        <el-form-item v-if="hasAuth('user:update')">
          <el-popover
              placement="right"
              v-model="showBachDisabledCard"
              width="180">
            <p style="color: red">确定批量{{DisableOrEnable}}这些用户吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="showBachDisabledCard = false;">取消</el-button>
              <el-button type="primary" size="mini"  @click="showBachDisabledCard = false;bachDisabled()">确定</el-button>
            </div>
            <el-button type="danger" slot="reference" v-show="!showDisableOrEnableButton">批量{{DisableOrEnable}}</el-button>
          </el-popover>
        </el-form-item>

        <el-form-item v-if="hasAuth('user:restpwd')">
          <el-popover
              placement="right"
              v-model="showBachRestCard"
              width="200">
            <p style="color: red">确定批量重置密码?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="showBachRestCard = false;">取消</el-button>
              <el-button type="primary" size="mini"  @click="showBachRestCard = false;bachRest()">确定</el-button>
            </div>
            <el-button type="danger" slot="reference" v-show="!showRestButton">批量重置密码</el-button>
          </el-popover>
        </el-form-item>

      </el-form>
    </div>

    <el-table
        v-if="hasAuth('user:list')" ref="userList"
        :data="userList" border @selection-change="selectionChange"
        style="width: 100%">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          fixed
          prop="username"
          label="用户名"
          width="110">
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名"
          width="110">
      </el-table-column>
      <el-table-column
          label="拥有角色"
          width="150"
          :filters="[{ text: '正常', value: true }, { text: '禁用', value: false }]"
          :filter-method="filterRoleTag"
          show-overflow-tooltip>
        <template slot-scope="scope">
          {{(scope.row.roleDescs?scope.row.roleDescs.split('|'):['无']).join('，')}}
        </template>
      </el-table-column>
      <el-table-column
          prop="address"
          label="住址"
          width="180"
          show-overflow-tooltip>
      </el-table-column>
      <el-table-column
          label="状态"
          width="70"
          :filters="[{ text: '正常', value: true }, { text: '禁用', value: false }]"
          :filter-method="filterStatueTag"
          filter-placement="bottom-end">
        <template slot-scope="scope">
          <el-tag :type="scope.row.statue?'success':'info'">{{scope.row.statue?'正常':'禁用'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="gender"
          label="性别"
          :filters="[{ text: '男性', value: false }, { text: '女性', value: true }]"
          :filter-method="filterGenderTag"
          width="80">
        <template slot-scope="scope">
          {{ scope.row.gender?'女':'男' }}
        </template>
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮件"
          width="180">
      </el-table-column>
      <el-table-column
          prop="phone"
          label="电话"
          width="150">
      </el-table-column>
      <el-table-column
          prop="loginCount"
          label="尝试次数"
          width="80">
      </el-table-column>
      <el-table-column
          prop="lastLoginTime"
          label="最后登录时间"
          width="180">
      </el-table-column>
      <af-table-column
          fixed="right"
          label="操作">
        <template slot-scope="scope">
          <el-button @click="updatePassword(scope.row.id)" type="text" size="small" v-if="hasAuth('user:updatepwd')">修改密码</el-button>
          <el-button @click="roleSet(scope.$index,scope.row.roleDescs,scope.row.id)" type="text" size="small" v-if="hasAuth('user:grantrole')">角色配置</el-button>
          <el-button @click="editUser(scope.$index,scope.row)" type="text" size="small" v-if="hasAuth('user:update')">编辑</el-button>
        </template>
      </af-table-column>
    </el-table>

    <div class="page">
      <el-pagination
          @size-change="userPageSizeChange"
          @current-change="userPageCurrentChange"
          :current-page="current"
          :page-sizes="[5, 10, 20, 30, 999]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

  <!--角色配置-->
    <el-dialog
        title="角色配置"
        :visible.sync="showRoleSetCard"
        :close-on-click-modal="false"
        width="25%"
        :before-close="roleSetCardClose">
      <el-checkbox-group v-model="userRole"  :border="true" size="medium">
        <el-checkbox style="display:block;" v-for="item in roleList" :label="item.roleDesc" :key="item.roleId"></el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleSetCardClose">取 消</el-button>
        <el-button type="primary" @click="okRoleSet">确 定</el-button>
      </span>
    </el-dialog>
  <!--编辑 新增-->
    <el-dialog
        title="用户信息"
        class="user-dialog"
        :visible.sync="showEditUserCard"
        :close-on-click-modal="false"
        width="40%"
        center
        :before-close="editUserCardClose">

      <el-form ref="userForm" status-icon :rules="userInfoRules" :model="user" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="user.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="user.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="user.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input v-model="user.address"></el-input>
        </el-form-item>
        <el-form-item label="状态" v-if="!editOrAddFlag">
          <el-switch class="radio-button-state"
              style="display: inline-block;margin-left: 20px"
              v-model="user.statue"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="正常"
              inactive-text="禁用">
          </el-switch>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="user.gender" :label="false" border>男</el-radio>
          <el-radio v-model="user.gender" :label="true" border>女</el-radio>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserCardClose">取 消</el-button>
        <el-button type="primary" @click="okEditUSer">确 定</el-button>
      </span>
    </el-dialog>

    <admin-footer/>
  </div>
</template>

<script>
import {
  bachRestPassword,
  bachStatueUser,
  getAllUserInfoAndRole,
  updateUser,
  addUser, updatePasswordByUserId, updateRoleByUserId
} from "@/network/adminUser";
import {getAllRoleSimple} from "@/network/role";
import AdminFooter from "@/components/conment/adminfooter/AdminFooter";
import {hasPermission} from "@/utils/mixin"
export default {
  name: "User",
  components: {AdminFooter},
  mixins:[hasPermission],
  data() {
    return {
      userList:[],//所有用户
      roleList:[],//所有角色
      userRole:[],//用户角色
      user:{},//修改的用户
      userIndex:0,//修改用户的数组序号
      temp:{},//临时变量
      tempArray:[],//临时变量
      editOrAddFlag:false,//修改还是新增标志变量
      showRoleSetCard:false,//显示角色编辑界面
      showEditUserCard:false,//显示编辑新增界面
      userInfoRules: {//表单验证
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入正确的电话', trigger: 'blur' },
          { min: 7, max: 11, message: '长度在 7 到 11 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 4, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
      },

      search:'',//搜索内容
      searchType:'name',//搜索类型

      showRestButton: true,
      showDisableOrEnableButton: true,//批量按钮
      showBachDisabledCard:false,//显示批量禁用
      DisableOrEnable:'',//
      showBachRestCard:false,//显示批量重置密码
      selectedRows:[],//选中的行

      size: 10,
      current:1,
      total:0,
    }
  },
  methods: {
    //角色修改页面展示
    roleSet(userIndex,userRole,userId) {
      //用户序号
      this.userIndex = userIndex
      this.userId = userId
      //用户拥有的角色信息填充
      this.userRole = userRole?userRole.split('|'):[]
      this.tempArray = userRole?userRole.split('|'):[]
      this.showRoleSetCard = true
    },
    //修改用户信息展示 新增用户也是这个函数
    editUser(userIndex,userInfo){
      //用户序号
      this.userIndex = userIndex
      //编辑用户
      if (userInfo){
        //编辑用户标志
        this.editOrAddFlag = false
        //深拷贝,防止数据绑定
        this.user = JSON.parse(JSON.stringify(userInfo))
        this.temp = userInfo
      }else {
        //新增用户标志
        this.editOrAddFlag = true
        //设置默认为男性
        this.$set(this.user,'gender',false)
      }
      this.showEditUserCard = true
    },
    //关闭角色修改页面
    roleSetCardClose(){
      this.userRole = []
      this.tempArray = []
      this.showRoleSetCard = false
    },
    //编辑card关闭//取消用户信息编辑
    editUserCardClose(){
      this.$refs.userForm.clearValidate()//表单验证清除
      this.user = {}
      this.temp = {}
      this.showEditUserCard = false
    },
    //修改 添加 用户
    okEditUSer() {
      this.$refs.userForm.validate( valid => {
        if (valid) {//表单验证成功
          if (this.editOrAddFlag) {
            addUser(this.user).then(res=>{
              if (res.data.code===200){
                this.getAllUserInfo(this.current,this.size,'','')
                this.$message.success('用户添加成功')
                this.editUserCardClose()
              }
            })
          } else {//编辑用户
            // this.$set(this.userList, this.userIndex, this.user)
            //判断是否修改过信息
            if (JSON.stringify(this.user) !== JSON.stringify(this.temp)) {
              updateUser(this.user).then(res => {
                if (res.data.code === 200) {
                  this.getAllUserInfo(this.current,this.size,'','')
                  this.$message.success('修改成功')
                } else {
                  this.$message.error('修改失败')
                }
              })
            }
            this.editUserCardClose()
          }
        } else {//表单验证失败
          console.log('表单验证失败')
        }
      })
    },
    //确认修改 权限
    okRoleSet(){
      if (JSON.stringify(this.tempArray) !== JSON.stringify(this.userRole)){
        let relUserRole = []
        this.userRole.forEach(myRole=> relUserRole.push((this.roleList.find(role=> role.roleDesc === myRole)).roleId))
        updateRoleByUserId(relUserRole,this.userId).then(res=>{
          this.getAllUserInfo(this.current,this.size,'','')
          this.$message.success("修改成功")
        })
      }
      this.roleSetCardClose()
    },
    //多选操作
    selectionChange(val){
      let enables = val.filter(res=>{
        return res.statue
      })
      let disables = val.filter(res=>{
        return !res.statue
      })
      //全是禁用用户
      if (Object.keys(enables).length === 0 && Object.keys(disables).length !== 0){
        this.DisableOrEnable = '启用'
        this.showDisableOrEnableButton = false
      }else if (Object.keys(enables).length !== 0 && Object.keys(disables).length === 0){
        this.DisableOrEnable = '禁用'
        this.showDisableOrEnableButton = false
      }else {
        this.showDisableOrEnableButton = true
      }
      this.selectedRows = val
      this.showRestButton = this.selectedRows.length === 0;
    },
    //批量禁用启用操作
    bachDisabled(){
      bachStatueUser(this.selectedRows.map(res=>res.id),this.DisableOrEnable==='启用'?'1':'0').then(res=>{
        if (res.data.code===200){
          this.$message.success("执行成功")
          //清除过滤
          this.$refs.userList.clearFilter();
          //更新数据
          this.getAllUserInfo(this.current,this.size,'','')
        }else
          this.$message.error("执行失败")
      })
      //清除选中状态
      this.$refs.userList.clearSelection()
    },
    //批量重置密码
    bachRest(){
      bachRestPassword(this.selectedRows.map(res=>res.id)).then(res=>{
        if (res.data.code===200){
          this.$message.success("执行成功,密码重置为："+res.data.data)
          //更新数据
          this.getAllUserInfo(this.current,this.size,'','')
        }else
          this.$message.error("执行失败")
      })
      //清除选中状态
      this.$refs.userList.clearSelection()
    },
    //根据用户信息搜索数据
    searchData(){
      //数据不为空
      if (this.search!==''){
        this.getAllUserInfo(this.current,this.size,this.searchType,this.search)
        if (this.userList.length===0)
          this.$message.info("未找到符合条件的数据")
      }else {
        this.$message.warning("请输入数据后再查询")
      }
    },
    //如果清除了数据就更新列表
    changeSearchInput(){
      if (this.search===''){
        this.getAllUserInfo(this.current,this.size,'','')
      }
    },
    //修改密码
    updatePassword(id){
      this.$prompt('请输入新密码', '提示', {
        type:'warning ',
        confirmButtonText: '确定',
        cancelButtonText: '取消',closeOnClickModal:false,
        roundButton: true,
        inputValidator:function (val){
          if (val == null || val.length <6 || val.length > 12) {
            return '长度在6-12';
          }
          if (!new RegExp(/^(?![^a-zA-Z]+$)(?!\D+$)/).test(val)) {
            return '必须包含至少一位数字和一位字母';
          }
        },

      }).then(({ value }) => {
        updatePasswordByUserId({id,'password':value}).then(res=>{
          if (res.data.code === 200){
            this.$message.success('密码修改成功')
          }else {
            this.$message.error('密码修改失败')
          }
        })
      }).catch(()=>{})
    },
    //过滤状态
    filterStatueTag(value, row){
      //清除选中状态
      this.$refs.userList.clearSelection()
      return row.statue === value
    },
    //过滤角色
    filterRoleTag(value, row){
      this.$refs.userList.clearSelection()
      return row.roleIds.split('|').findIndex(res=>res===value)
    },
    //过滤性别
    filterGenderTag(value, row){
      //清除选中状态
      this.$refs.userList.clearSelection()
      return row.gender === value
    },
    //每页数据条数改变
    userPageSizeChange(val){
      this.size = val
      this.getAllUserInfo(this.current,this.size,'','')
    },
    //页数改变
    userPageCurrentChange(val){
      this.current = val
      this.getAllUserInfo(this.current,this.size,'','')
    },
    //匹配实际角色
    getUserRole(roleIds){
      return roleIds?roleIds.split('|').map(res=> (this.roleList.find(f=>f.roleId === parseInt(res))).roleDesc):[]
    },
    getAllUserInfo(current,size,searchType,search){
      //获取所有用户信息
      getAllUserInfoAndRole(current,size,searchType,search).then(res=>{
        if (res.data.data.records.length === 0)
          this.$message.warning("未找到符合条件的数据")
        else{
          this.userList = res.data.data.records
          this.size = res.data.data.size
          this.current = res.data.data.current
          this.total = res.data.data.total
        }
      })
    }
  },
  created() {
    this.getAllUserInfo(this.current,this.size,'','')
    //获取所有角色信息
    getAllRoleSimple().then(res=>{
      this.roleList = res.data.data
    })
  },
}
</script>

<style scoped>
  .radio-button-state span {
    display: inline-block;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

</style>